//
//  UIUserRegViewController.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/7/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UIUserRegViewController.h"
#import "UICodeVerifyViewCtrl.h"
#import "UILoginViewController.h"

//test
#import "UIRegProfileViewCtrl.h"
#import "StatusBarColorManager.h"

//#import "ImgSwipeViewController.h"

//static int _nImgIdx = 0;
//static int _nImgCount = 4;
//static BOOL _bDesImgIdx = NO;
//static NSTimer* _imgChgTimer = nil;
#define  CFFont(fontSize) Regular(16)
@interface UIUserRegViewController ()

@end

@implementation UIUserRegViewController {
    //UILabel* lblMsg;
  UILabel* _lblCreateTips;
  UIButton* _btnAlreadyUser;
  
  UILabel* _lblFirstNameTip;
  UITextField* _txtFirstName;
  
  UILabel* _lblLastNameTip;
  UITextField* _txtLastName;
  
  UILabel* _lblEmailBoxTip;
  UITextField* _txtEmailBox;
  
  UILabel* _lblPasswordTip;
  UITextField* _txtPassword;
  
  UILabel* _lblCnfrPswdTip;
  UITextField* _txtCnfrPswd;
    
  UIButton* _btnRegSubmit;
  UIActivityIndicatorView* _actView;
    
  UILabel* _lblMsg;
  
  UILabel* _lblConnSvrTip;
  UISegmentedControl* _scSvrIpIdx;
  
  BOOL _biPad;
  BOOL _biP6p;
  BOOL _biP5s;
  BOOL _bWider;
  
  //ImgSwipeViewController* _imgSwpViewCtrl;
  
  //UILabel* _lblFitFips;
  //UILabel* _lblTrackerTips;
  
  //UIButton* _btnRegUser;
  //UIButton* _btnLoginUser;
 // UIPageControl* _pageC;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  /*pApp.m_pNavController.toolbarHidden = YES;
  if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
    // iOS 7
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
  } else {
    // iOS 6
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
  }
  [[UIApplication sharedApplication] setStatusBarHidden:YES];*/
  //[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
  //self.navigationController.delegate = self;
  
  CGRect frame = [[UIScreen mainScreen] bounds];
  //UICoordinateSpace space = [[UIScreen.mainScreen.coordinateSpace];
  float fScale = [UIScreen mainScreen].scale;
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  
  _biPad = H > 1000;
  _biP6p = fScale >= 3.0;
  _biP5s = H >= 568 && W == 320;
 _bWider = W > 320;
  
  CGRect rt = self.view.window.bounds;
  rt.origin.y -= 44;
  self.view.frame = rt;
  //UIImage* imgback = [pApp getImageScale:(_biPad?@"ic-Launch@1024.png":@"ic-launch4.png") scale:(_biPad?1.0:_biP6p? 0.40:0.32)];
  //UIImage* imgback = [pApp getImageScale:@"ic-launch1.png"  scale:(_biPad? 1.30:_biP6p? 1.0: 0.64)];
  UIImage* imgback = [pApp getImageScale:@"ic-reg1.png"  scale:(_biPad? 1.00:_biP6p? 0.5: 0.40)];
  [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
  
  [self createRegUserInfoUi:W h:H];
  
  //CGFloat xPos = (W-260)/ 2.0;//_biPadDev? :20;
  //CGFloat yPos = H * 0.75; //_biPad? H / 1.60: H / (_bWider?0.50: 0.42) + (_biP5s? 45:30);
  //_btnRegUser = [[UIButton alloc] initWithFrame:CGRectMake(xPos, yPos, 260, 30)];
  /*_lblFitFips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, H * 0.4, W-xPos*2, 30)];
  _lblFitFips.font = [UIFont boldSystemFontOfSize:_biPad? 40.0: (_bWider?30: 28.0)];
  _lblFitFips.textColor = [UIColor whiteColor];
  _lblFitFips.textAlignment = NSTextAlignmentLeft;
  _lblFitFips.text = @"F.I.T.";
  [self.view addSubview:_lblFitFips];
  
  
  _lblTrackerTips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, H * 0.4 + 30, 260 + (_biPad?100:0), 30)];
  _lblTrackerTips.font = [UIFont boldSystemFontOfSize:_biPad? 20.0: (_bWider?15: 13.0)];
  _lblTrackerTips.textColor = [UIColor whiteColor];
  _lblTrackerTips.textAlignment = NSTextAlignmentLeft;
  _lblTrackerTips.text = @"You Personal Fitness Tracker";
  [self.view addSubview:_lblTrackerTips];
  
  _btnRegUser = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnRegUser.frame = CGRectMake(xPos, yPos, 260, 30);
  [_btnRegUser setTitle:@"Creater an Account" forState:UIControlStateNormal];
  _btnRegUser.tintColor = [UIColor whiteColor];
  _btnRegUser.backgroundColor = [UIColor orangeColor];
  _btnRegUser.layer.cornerRadius = 4;
  [_btnRegUser addTarget:self action:@selector(onRegCreate:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnRegUser];
  
  yPos += 50;
  _btnLoginUser = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnLoginUser.frame = CGRectMake(xPos, yPos, 260, 30);
  //_btnRegUser.titleLabel.text = @"Register User";
  [_btnLoginUser setTitle:@"Login to Fit" forState:UIControlStateNormal];
  _btnRegUser.tintColor = [UIColor whiteColor];
  _btnLoginUser.backgroundColor = [UIColor redColor];
  _btnLoginUser.layer.cornerRadius = 4;
  [_btnLoginUser addTarget:self action:@selector(onLoginUser:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnLoginUser];*/
  
  _actView = nil;
  
  //_imgSwpViewCtrl = nil;
  //[self setupSwipeGesture];
  
//  [[StatusBarColorManager sharedStatusBarColorManager] setWindowColor:[UIColor blackColor]];
//  self.navigationController.navigationBar.backgroundColor = [UIColor grayColor];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

/*- (void) navigationController:(UINavigationController*) navigationController willShowViewController:(nonnull UIViewController *)viewController animated:(BOOL)animated
{
  BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
  [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}


- (BOOL) prefersStatusBarHidden {
  return YES;
}*/

/*- (void) viewDidLayoutSubviews
{
  CGFloat fScale = [UIScreen mainScreen].scale;
  CGFloat fHgtDelta = (fScale >= 3.0)? 4: 0;
  CGRect frame = self.navigationController.navigationBar.frame;
  frame.size.height -= fHgtDelta;
  [self.navigationController.navigationBar setFrame:frame];
}*/
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_btnRegSubmit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

- (void) createRegUserInfoUi:(CGFloat) W h:(CGFloat)H
{
  CGFloat xPos = _biPad? 120:20;
  CGFloat yPos = _bWider? 90: 80;
  _lblCreateTips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos - 14, W-xPos*2, 30)];
    _lblCreateTips.font = Bold(16);
  _lblCreateTips.textColor = [UIColor whiteColor];
  _lblCreateTips.textAlignment = NSTextAlignmentCenter;
  _lblCreateTips.text = NSLocalizedString(@"CreateAnAcct", nil);//@"CREATE AN ACCOUNT";
  [self.view addSubview:_lblCreateTips];
  
  xPos += W/3.0 + (_biPad?25:(_bWider? 50: 40));
  _btnAlreadyUser = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnAlreadyUser.frame = CGRectMake(xPos+15, H-60, W/3.0+(_bWider?40:30), 30);
  //[_btnAlreadyUser setImageEdgeInsets:UIEdgeInsetsMake(-4.0, -8, 0.0, 0.0)];
  [_btnAlreadyUser setTitle:NSLocalizedString(@"AlreadyAuser", nil)/*@"Already a user?"*/ forState:UIControlStateNormal];
  _btnAlreadyUser.titleLabel.font = [UIFont systemFontOfSize:_biPad?24: (_bWider?18 :14)];
  //_btnAlreadyUser.backgroundColor = [UIColor lightGrayColor];
  //_btnRegTag.layer.masksToBounds = YES;
  //_btnAlreadyUser.layer.cornerRadius = 4;
  [_btnAlreadyUser setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
  [_btnAlreadyUser addTarget:self action:@selector(onAlreadyUser:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview: _btnAlreadyUser];
  _btnAlreadyUser.hidden = YES;
  
  [self initViewCtrls:W hgt:H];
  
  xPos = (W-300)/ 2.0;//_biPadDev? :20;
  yPos = _biPad? H / 1.60: H / (_bWider?1.20: 1.18) + (_biP5s? 30:10);
  _btnRegSubmit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnRegSubmit.frame = CGRectMake(15, H - (H / 16.7) - 20, W - 30, H / 16.7);
  _btnRegSubmit.titleLabel.font = [UIFont systemFontOfSize:_biPad?16:13];
  //[_btnRegSubmit setBackgroundImage:[UIImage imageNamed:@"btn-submit.png"] forState:UIControlStateNormal];
  //[_btnRegSubmit setImageEdgeInsets:UIEdgeInsetsMake(-4.0, -8, 0.0, 0.0)];
  _btnRegSubmit.backgroundColor = [UIColor colorWithRed:45.0/255 green:212.0/255 blue:201.0/255 alpha:1.0];
  _btnRegSubmit.layer.cornerRadius = 8;
  _btnRegSubmit.tintColor = [UIColor whiteColor];
  [_btnRegSubmit setTitle:NSLocalizedString(@"SignUp", nil)/*@"SIGN UP"*/ forState:UIControlStateNormal];
  _btnRegSubmit.titleLabel.font = Regular(16);
  //_btnRegSubmit.backgroundColor = [UIColor lightGrayColor];
  //_btnRegTag.layer.masksToBounds = YES;
  //_btnRegSubmit.layer.cornerRadius = 4;
  //[_btnRegSubmit setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  [_btnRegSubmit addTarget:self action:@selector(onRegSubmit:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnRegSubmit];
  
  yPos += 40;
  _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, W-xPos*2, 30)];
  _lblMsg.font = [UIFont systemFontOfSize: _biPad? 20.0: (_bWider?15: 13.0)];
  _lblMsg.textColor = [UIColor redColor];
  _lblMsg.textAlignment = NSTextAlignmentLeft;
  _lblMsg.text = @"";
//  [self.view addSubview:_lblMsg];
  
//  UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//  [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnRegWait:) forControlEvents:UIControlEventTouchUpInside];
//  
//  //UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRedo target:self action:@selector(onRtnRegWait:)];
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
  self.navigationItem.rightBarButtonItem = nil;

  [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
}

/*-(void) onRegCreate:(id)sender
{00
  if(_imgChgTimer != nil) {
    [_imgChgTimer invalidate];
  }
  
  _lblFitFips.hidden = YES;
  _lblTrackerTips.hidden = YES;
  
  _btnRegUser.hidden = YES;
  _btnLoginUser.hidden = YES;
  
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  [self createRegUserInfoUi:W h:H];
}

- (void) onLoginUser:(id)sender
{
  _lblFitFips.hidden = YES;
  _lblTrackerTips.hidden = YES;
  
  _btnRegUser.hidden = YES;
  _btnLoginUser.hidden = YES;
  //_lblMsg.text = @"Login";
  [self onAlreadyUser:sender];
}*/

- (void) initViewCtrls:(CGFloat) W hgt:(CGFloat)H {
  BOOL bIpad = _biPad ;//H > 1000;
  BOOL bHigt = H > 480;
  //BOOL bIp6p = _biP6p;
  CGFloat xPos = bIpad? 120: 15;
  CGFloat yPos = bIpad? 125: (bHigt? 95: 85);
  if(W > 320)
    yPos += 20;
  CGFloat fWid = W - xPos * 2;
  CGFloat fHgt = bIpad? 36: (bHigt?30:20);
  CGFloat fDelta = bIpad?50: (bHigt?30: 24);
    int lableH = 20;
    int disH = 5;
    fHgt = H / 16.7;
  _lblFirstNameTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, 127, fWid, lableH)];
  _lblFirstNameTip.textColor = [UIColor whiteColor];
    _lblFirstNameTip.font = CFFont(fontSize);
  _lblFirstNameTip.text = NSLocalizedString(@"FirstName", nil);//@"First Name";
  [self.view addSubview: _lblFirstNameTip];
  
  yPos += 26;
  _txtFirstName = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblFirstNameTip.frame) + disH, fWid, fHgt)];
  _txtFirstName.textColor = [UIColor whiteColor];
  _txtFirstName.backgroundColor = [UIColor clearColor];
  _txtFirstName.font = [UIFont systemFontOfSize:bIpad?20:16];
  _txtFirstName.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtFirstName.layer.cornerRadius = 6.0f;
  _txtFirstName.layer.borderWidth = 1.0f;
  _txtFirstName.layer.borderColor = [UIColor whiteColor].CGColor;
  
  _txtFirstName.keyboardType = UIKeyboardTypeEmailAddress;
  _txtFirstName.placeholder = @"";//NSLocalizedString(@"FirstName", nil);//@"First Name"; //NSLocalizedString(@"Name", nil);
  [self.view addSubview: _txtFirstName];
    
    //last name
  yPos += fDelta;
  _lblLastNameTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtFirstName.frame) + disH, fWid, lableH)];
  _lblLastNameTip.textColor = [UIColor whiteColor];
  _lblLastNameTip.font = CFFont(fontSize);
  _lblLastNameTip.text = NSLocalizedString(@"LastName", nil);//@"Last Name";
  [self.view addSubview: _lblLastNameTip];

  yPos += 26;
  _txtLastName = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblLastNameTip.frame) + disH, fWid, fHgt)];
  _txtLastName.textColor = [UIColor whiteColor];
  _txtLastName.backgroundColor = [UIColor clearColor];
  _txtLastName.font = [UIFont systemFontOfSize:bIpad?20:16];
  _txtLastName.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtLastName.layer.cornerRadius = 6.0f;
  _txtLastName.layer.borderWidth = 1.0f;
  _txtLastName.layer.borderColor = [UIColor whiteColor].CGColor;

  
  _txtLastName.keyboardType = UIKeyboardTypeEmailAddress;
  _txtLastName.placeholder = @"";//NSLocalizedString(@"LastName", nil); //@"Last Name"; //NSLocalizedString(@"Name", nil);
  [self.view addSubview: _txtLastName];
    
    //email
  yPos += fDelta;
  _lblEmailBoxTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtLastName.frame) + disH, fWid, lableH)];
  _lblEmailBoxTip.textColor = [UIColor whiteColor];
  _lblEmailBoxTip.font = CFFont(fontSize);
  _lblEmailBoxTip.text = @"Email";
  [self.view addSubview: _lblEmailBoxTip];

  yPos += 26;
  _txtEmailBox = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblEmailBoxTip.frame) + disH, fWid, fHgt)];
  _txtEmailBox.textColor = [UIColor whiteColor];
  _txtEmailBox.backgroundColor = [UIColor clearColor];
  _txtEmailBox.font = [UIFont systemFontOfSize:bIpad?20:16];
  _txtEmailBox.borderStyle = UITextBorderStyleRoundedRect;

  _txtEmailBox.layer.cornerRadius = 6.0f;
  _txtEmailBox.layer.borderWidth = 1.0f;
  _txtEmailBox.layer.borderColor = [UIColor whiteColor].CGColor;
  
  _txtEmailBox.autocapitalizationType = UITextAutocapitalizationTypeNone;
  _txtEmailBox.keyboardType = UIKeyboardTypeEmailAddress;
  _txtEmailBox.placeholder = @"";//@"E-mail"; //NSLocalizedString(@"Name", nil);
  [self.view addSubview: _txtEmailBox];
    
    //pswd and confirm
  yPos += fDelta;
  
  _lblPasswordTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtEmailBox.frame) + disH, fWid, lableH)];
  _lblPasswordTip.textColor = [UIColor whiteColor];
  _lblPasswordTip.font = CFFont(fontSize);
  _lblPasswordTip.text = NSLocalizedString(@"Password", nil);//@"Password";
  [self.view addSubview: _lblPasswordTip];
  
  yPos += 26;
  _txtPassword = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblPasswordTip.frame) + disH, fWid, fHgt)];
  _txtPassword.textColor = [UIColor whiteColor];
  _txtPassword.backgroundColor = [UIColor clearColor];
  _txtPassword.font = [UIFont systemFontOfSize:bIpad?20:16];
  _txtPassword.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtPassword.layer.cornerRadius = 6.0f;
  _txtPassword.layer.borderWidth = 1.0f;
  _txtPassword.layer.borderColor = [UIColor whiteColor].CGColor;

  
  //_txtPassword.keyboardType = UIKeyboardTypeP;
  _txtPassword.placeholder = @"";//NSLocalizedString(@"Password", nil);//@"Password";
  _txtPassword.secureTextEntry = YES;
  [self.view addSubview:_txtPassword];
    
  yPos += fDelta;
  _lblCnfrPswdTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtPassword.frame) + disH, fWid, lableH)];
  _lblCnfrPswdTip.textColor = [UIColor whiteColor];
  _lblCnfrPswdTip.font = CFFont(fontSize);
  _lblCnfrPswdTip.text = NSLocalizedString(@"ConfirmPswd", nil);//@"Confirm Password";
  [self.view addSubview: _lblCnfrPswdTip];
  
  yPos += 26;
  _txtCnfrPswd = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblCnfrPswdTip.frame) + disH, fWid, fHgt)];
  _txtCnfrPswd.textColor = [UIColor whiteColor];
  _txtCnfrPswd.backgroundColor = [UIColor clearColor];
  _txtCnfrPswd.font = [UIFont systemFontOfSize:bIpad?20:16];
  _txtCnfrPswd.borderStyle = UITextBorderStyleRoundedRect;
  
  _txtCnfrPswd.layer.cornerRadius = 6.0f;
  _txtCnfrPswd.layer.borderWidth = 1.0f;
  _txtCnfrPswd.layer.borderColor = [UIColor whiteColor].CGColor;
  
  _txtCnfrPswd.placeholder = @"";//NSLocalizedString(@"ConfirmPswd", nil);//@"Confirm Password";
  _txtCnfrPswd.secureTextEntry = YES;
  [self.view addSubview:_txtCnfrPswd];
  
  yPos += fDelta;
  _lblConnSvrTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtCnfrPswd.frame) + disH, bIpad?180:130, lableH)];
  _lblConnSvrTip.font = [UIFont systemFontOfSize: bIpad? 18.0: 14.0];
  _lblConnSvrTip.textColor = [UIColor whiteColor];
  _lblConnSvrTip.textAlignment = NSTextAlignmentLeft;
  _lblConnSvrTip.text = @"Reg. SVR. Address:";
  [self.view addSubview:_lblConnSvrTip];
  _lblConnSvrTip.hidden = YES;
  
  xPos += bIpad?80:20;
  CGFloat fWidth = W - 2 * xPos;
  _scSvrIpIdx = [[UISegmentedControl alloc] initWithItems:@[@"Americas", @"International"]];
  _scSvrIpIdx.frame = CGRectMake(xPos, yPos, fWidth, 28);
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  Byte nIdx = pApp.m_bodyInfo.nSvrIpIdx;
  _scSvrIpIdx.selectedSegmentIndex = nIdx;
  [self.view addSubview:_scSvrIpIdx];
  
  _scSvrIpIdx.selectedSegmentIndex = 1;
  _scSvrIpIdx.hidden = YES;
}

/*- (void) onImgCheTimer
{
  [self changeViewCtrlBkgdImg];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblCreateTips.text = @"No enough memory!";
  AudioServicesPlaySystemSound(1112);
}*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void) onRegSubmit:(id)sender
{
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  self.navigationItem.hidesBackButton = YES;
  pApp.m_pNavController.navigationItem.hidesBackButton = YES;
  
  //test
  /*[pApp saveRegBodyInfo:39 email:@"test@gmail.com" first:@"firstne" last:@"lastne" tagId:@"sTagId"];
  UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UICodeVerifyViewCtrl * vcCodeVerify = [mainStory instantiateViewControllerWithIdentifier:@"codeVerifyViewCtrl"];
  [pApp.m_pNavController pushViewController:vcCodeVerify animated:YES];
  return;*/
  //test
    
  _lblMsg.text = @"";
  NSString* sFirst = _txtFirstName.text;
  NSString* sLast = _txtLastName.text;
  
  NSString* sEmail = _txtEmailBox.text;
  NSString* sPswd = _txtPassword.text;
  
  if(sEmail.length == 0 || sPswd.length == 0) {
    _lblCreateTips.text = @"Email & Pswd not Empty!";
    AudioServicesPlaySystemSound(1112);
    return;
  }
  NSString* sCnfrPswd = _txtCnfrPswd.text;
  if(![sPswd isEqualToString:sCnfrPswd]) {
    _lblCreateTips.text = @"Password does not match!";
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  NSInteger nIdx = _scSvrIpIdx.selectedSegmentIndex;
  NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  [userSetting setInteger:nIdx forKey:kReg_BodySvrIdx];
  [pApp updSvrIpAddress:(short)nIdx];
  
  [self regUserInfoOnSvr:sFirst last:sLast email:sEmail pswd:sPswd];
}
     
- (void) regUserInfoOnSvr:(NSString*)sFirst last:(NSString*)sLast email:(NSString*)sEmail pswd:(NSString*) sPswd
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
    //_lblCreateTips.text = [NSString stringWithFormat:@"%@, %@, %@, %@", sFirst, sLast, sEmail, sPswd];
  
    if(_actView == nil) {
        CGRect rt = _btnRegSubmit.frame;
        rt.origin.x += rt.size.width - rt.size.height * 2;
        rt.size.width = rt.size.height;
        _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
        _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        _actView.hidesWhenStopped = YES;
        [self.view addSubview:_actView];
    }
    _btnRegSubmit.hidden = YES;
    [_actView startAnimating];
    
    // 4.设置请求体（请求参数）
    // 创建一个描述订单信息的JSON数据
    NSDictionary *regInfo = @{
                                @"BodyId" : @"-3",
                                @"Email" : sEmail,
                                @"Password" : sPswd,
                                @"FirstName": sFirst,
                                @"LastName" : sLast,
                                @"m_nComIdx": @"2"
                                };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Mob" data:regInfo];
    
    
    // 6.发送请求
    //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil || connectionError)
            return;
        
        //NSString* sRecv = [data description];
        NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        //sRecv = [sRecv substringFromIndex:1];
        sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
        if([sRecv hasPrefix:@"Sorry"]) {
            //if([sRecv )
          sRecv = [sRecv stringByReplacingOccurrencesOfString:@"username" withString:@"E-mail"];
          [_actView stopAnimating];
          _btnRegSubmit.hidden = NO;
          _lblMsg.text = sRecv;
          AudioServicesPlaySystemSound(1109);
          return;
        }
        NSArray *listItems = [sRecv componentsSeparatedByString:@":"];
        NSUInteger nCount = listItems.count;
        if(nCount > 1) {
          NSString* sBodyId = listItems[1];
          int nBodyId = sBodyId.intValue;
          NSString* sTagId = @"";
          
          if(nBodyId > 0) {
            [pApp saveRegBodyInfo:nBodyId email:sEmail first:sFirst last:sLast tagId:sTagId];
            UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UICodeVerifyViewCtrl * vcCodeVerify = [mainStory instantiateViewControllerWithIdentifier:@"codeVerifyViewCtrl"];
            [pApp.m_pNavController pushViewController:vcCodeVerify animated:YES];
          }
          else {
            _lblMsg.text = @"Register failed! Please try later!";
          }
        }
        else {
            _lblMsg.text = @"Register failed! Please try later!";
        }
        
        [_actView stopAnimating];
        _btnRegSubmit.hidden = NO;
    }];
}

- (void) onAlreadyUser:(id)sender
{
  UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UILoginViewController* vcLogin = [mainStory instantiateViewControllerWithIdentifier:@"loginViewCtrl"];
  vcLogin.bLoguot = NO;
  
  //test
  //®UIRegProfileViewCtrl* vcLogin = [mainStory instantiateViewControllerWithIdentifier:@"userProfViewCtrl"];
    
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp.m_pNavController popToRootViewControllerAnimated:NO];
  [pApp.m_pNavController pushViewController:vcLogin animated:YES];
}

- (void) onRtnRegWait:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp enterPageWithRes:@"userRegWaitVC"];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    if([_txtFirstName isFirstResponder])
        [_txtFirstName resignFirstResponder];
    else if([_txtLastName isFirstResponder])
        [_txtLastName resignFirstResponder];
    else if([_txtEmailBox isFirstResponder])
        [_txtEmailBox resignFirstResponder];
    else if([_txtEmailBox isFirstResponder])
        [_txtEmailBox resignFirstResponder];
    else if([_txtPassword isFirstResponder])
        [_txtPassword resignFirstResponder];
    else if([_txtCnfrPswd isFirstResponder])
        [_txtCnfrPswd resignFirstResponder];
}

@end
